<template>
  <div class="app-container mod-hot-search">
    <!-- 搜索相关区域 -->
    <div class="filter-container">
      <el-form ref="pageQuery" :inline="true" :rules="rules" :model="pageQuery" class="demo-form-inline">
        <el-form-item label="吧台类型" label-width="80px" prop="type">
          <el-select
            v-model="pageQuery.type"
            size="mini"
            placeholder="请选择吧台类型"
            clearable
          >
            <el-option label="自营" value="1" />
            <el-option label="联营" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="吧台编号" label-width="80px" prop="number">
          <el-input
            disabled
            style="width: 180px"
            v-model="pageQuery.number"
            size="mini"
            placeholder="请输入吧台编号"
          />
        </el-form-item>
        <el-form-item label="投放区域" label-width="80px" prop="barCounterShopId">
          <el-select
            v-model="pageQuery.barCounterShopId"
            size="mini"
            placeholder="请选择投放区域"
            clearable
            @change="barCounterChange"
          >
            <el-option
              v-for="(item, index) in barCounterShopList"
              :key="index"
              :label="item.barCounterRegion"
              :value="item.barCounterShopId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="投资人" label-width="80px" prop="investorId">
          <el-select
            v-model="pageQuery.investorId"
            size="mini"
            placeholder="请选择投资人"
            clearable
          >
            <el-option
              v-for="(item, index) in investorList"
              :key="index"
              :label="item.investorName"
              :value="item.barCounterInvestorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" label-width="80px" prop="phone">
          <el-input
            style="width: 180px"
            v-model="pageQuery.phone"
            size="mini"
            placeholder="请输入联系方式"
          />
        </el-form-item>
        <el-form-item label="分账比例" label-width="80px" prop="allocationRatio">
          <el-input
            style="width: 180px"
            v-model="pageQuery.allocationRatio"
            size="mini"
            placeholder="请输入分账比例"
          />
        </el-form-item>
      </el-form>
      <el-button
        v-permission="['']"
        size="mini"
        icon="el-icon-plus"
        plain
        type="primary"
        class="filter-item"
        @click="showInput"
        >货柜</el-button
      >
    </div>
    <div class="container">
      <el-tag
        :key="index"
        v-for="(tag, index) in pageQuery.barCounterContainerDTOList"
        :effect="tagIndex == index ? 'dark' : 'plain'"
        @click="status(index)"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
        style="margin-right: 10px"
      >
      {{ tag.region }}
      </el-tag>
      <el-input
        v-if="inputVisible"
        placeholder="请添加货柜"
        style="width: 100px; margin-left: 10px; vertical-align: bottom"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
      />
    </div>
    <el-button
      v-permission="['']"
      size="mini"
      icon="el-icon-plus"
      type="primary"
      class="filter-item"
      @click="handleAddShop()"
      v-if="pageQuery.barCounterContainerDTOList.length > 0"
      style="margin-bottom: 10px"
      >批量录入商品</el-button
    >
    <!-- 列表相关区域 -->
    <el-table
      v-if="pageQuery.barCounterContainerDTOList.length > 0"
      :data="pageQuery.barCounterContainerDTOList[tagIndex].barSpuDTOList"
      border
      fit
      style="width: 100%"
      :row-key="(id) => id.spuId"
    >
      <!-- 吧台类型 -->
      <!-- <el-table-column label="吧台类型" prop="content" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.content }}</span>
        </template>
      </el-table-column> -->
      <!-- 所属商品 -->
      <el-table-column label="所属商品" prop="name" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <!-- 商品规格 -->
      <el-table-column label="商品规格" prop="skuName" align="center">
        <template slot-scope="{ row }">
          <span>{{ (row.barSkuDTOList && row.barSkuDTOList.length > 0) ? row.barSkuDTOList[0].skuName : '' }}</span>
        </template>
      </el-table-column>
      <!-- 库存 -->
      <!-- <el-table-column label="库存" prop="totalStock" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.totalStock || (row.barSpuDTOList && row.barSpuDTOList.length > 0) ? (row.barSkuDTOList && row.barSkuDTOList.length > 0) ? row.barSkuDTOList[0].stock : '' : '' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间" prop="createTime" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime ? row.createTime : nowDate }}</span>
        </template>
      </el-table-column>
      <!-- 预警线 -->
      <el-table-column label="预警线" prop="alermLine" align="center">
        <template slot-scope="{ row }">
          <span>{{ (row.barSkuDTOList && row.barSkuDTOList.length > 0) ? row.barSkuDTOList[0].alermLine : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            v-permission="['']"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            v-permission="['']"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleDel($index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="float: right; margin-top: 10px;">
      <el-button type="primary" @click="onsave()"> 确定 </el-button>
    </div>
    <el-dialog title="批量录入商品" width="1400px" :visible.sync="visibleShop">
      <el-form
        ref="dataFormShop"
        :model="dataFormShop"
        label-position="right"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="所属货柜：" prop="region">
          <el-select
            v-model="dataFormShop.region"
            multiple
            placeholder="请选择所属货柜"
            style="width: 30%"
          >
            <el-option
              v-for="item in pageQuery.barCounterContainerDTOList"
              :key="item.region"
              :label="item.region"
              :value="item.region"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属商品：" prop="">
          <el-input v-model="pageQuerys.name" style="width: 30%" @keyup.enter.native="getShopList()" @blur="getShopList()" placeholder="请输入关键词"/>
          <div style="margin-top: 10px">
            <el-table
              ref="prodInfTable"
              :data="pageVO.list"
              :header-cell-style="{background:'#f9f9f9',color:'#606266'}"
              border
              height="300px"
            >
              <el-table-column width="80">
                <template slot-scope="{row}">
                  <div>
                    <el-radio
                      :label="row.spuId"
                      v-model="singleSelectBrandId"
                      @change.native="getSelectBrandRow(row)"
                    ></el-radio>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                class="table-item"
                prop="name"
                label="商品名称"
                align="center"
              />
               <!-- 规格 -->
               <el-table-column class="table-item" width="250" prop="barSpuId" label="规格">
                <template slot-scope="{ row }">
                  <el-select
                    v-model="row.guige"
                    size="mini"
                    placeholder="请选择商品规格"
                    @focus="onFocus(row)"
                    @change="(e) => {skuChange(e, row)}"
                  >
                    <el-option
                      v-for="item in skuList"
                      :key="item.barSpuId"
                      :label="item.skuName"
                      :value="item.skuId"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <!-- 预警线 -->
              <el-table-column class="table-item" width="200" prop="barSpuId" label="预警线">
                <template slot-scope="{ row }">
                  <el-input-number
                    style="width: 150px"
                    v-model="row.alermLine"
                    controls-position="right"
                    :precision="0"
                  />
                </template>
              </el-table-column>
              <!-- 当前价 -->
              <el-table-column
                class="table-item"
                prop="priceFee"
                label="当前价"
              >
                <template slot-scope="scope">
                  <div class="prod-price-box">
                    <div slot="reference" class="name">{{ scope.row.priceFee }}</div>
                  </div>
                </template>
              </el-table-column>
              <!-- 市场价 -->
              <el-table-column
                class="table-item"
                prop="marketPriceFee"
                label="市场价"
              />
              <!-- 累计销量 -->
              <el-table-column
                class="table-item"
                prop="saleNum"
                label="累计销量"
              />
              <!-- 库存 -->
              <el-table-column
                class="table-item"
                prop="totalStock"
                label="库存"
              />
              <!-- 商品状态状态 1:enable, 0:disable, -1:deleted -->
              <el-table-column label="商品状态" prop="status" align="center">
                <template slot-scope="{row}">
                  <el-tag v-if="row.status === 0" size="small" type="danger">下架</el-tag>
                  <el-tag v-if="row.status === 1" size="small">上架</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
            <!-- 分页条 -->
          <pagination
            v-show="pageVO.total > 0"
            :total="pageVO.total"
            :page.sync="pageQuerys.pageNum"
            :limit.sync="pageQuerys.pageSize"
            @pagination="getShopList()"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visibleShop = false"> 取消 </el-button>
        <el-button type="primary" @click="shopSubmit()"> 确定 </el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="visible">
      <el-form
        ref="dataForm"
        :model="dataForm"
        label-position="right"
        label-width="80px"
      >
        <!-- 商品图片 -->
        <el-form-item label="商品图片" prop="mainImgUrl">
          <img-upload v-model="dataForm.mainImgUrl" />
        </el-form-item>
        <!-- 商品状态 -->
        <el-form-item label="商品状态" prop="spuStatus">
          <el-select v-model="dataForm.status" placeholder="请选择商品状态">
            <el-option label="上架" :value="1"></el-option>
            <el-option label="下架" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 商品规格 -->
        <el-form-item label="商品规格" prop="marketPriceFee">
          <el-select
            style="width: 202px"
            v-model="dataForm.guige"
            size="mini"
            placeholder="请选择商品规格"
            @focus="onFocus(dataForm)"
          >
            <el-option
              v-for="item in skuList"
              :key="item.barSpuId"
              :label="item.skuName"
              :value="item.barSkuId"
            />
          </el-select>
        </el-form-item>
        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="marketPriceFee">
          <el-input style="width: 202px" v-model="dataForm.marketPriceFee" />
        </el-form-item>
        <!-- 库存预警 -->
        <el-form-item label="库存预警" prop="alermLine">
          <el-input-number
            v-model="dataForm.alermLine"
            controls-position="right"
            :precision="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false"> 取消 </el-button>
        <el-button type="primary" @click="dataFormSubmit()"> 确定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
    
<script>
import permission from "@/directive/permission/index.js";
import Pagination from "@/components/Pagination";
import ImgUpload from "@/components/ImgUpload";
import * as api from "@/api/selfoperated/index";
import * as api_shop from '@/api/product/list'
import * as api_sku from '@/api/product/prod-info';
import moment from 'moment';

export default {
  name: "",
  components: { Pagination, ImgUpload },
  directives: { permission },
  data() {
    const self = this
    return {
      // 查询的参数
      pageQuery: {
        type: null,
        number: null,
        investorId: null,
        phone: null,
        allocationRatio: null,
        barCounterShopId: null,
        barCounterContainerDTOList: []
      },
      pageQuerys: {
        pageSize: 10,
        pageNum: 1,
      },
      // 返回参数
      pageVO: {
        list: [], // 返回的列表
        total: 0, // 一共多少条数据
        pages: 0, // 一共多少页
      },
      // 查询参数
      searchParam: {},
      visible: false,
      visibleShop: false,
      inputVisible: false,
      singleSelectBrandId: 0,
      brandListSelections: {},
      rules: {
        region: [{ required: true, message: '请选择所属柜台', trigger: 'blur' }],
        type: [{ required: true, message: '请选择吧台类型', trigger: 'blur' }],
        number: [{ required: true, message: '请输入吧台编号', trigger: 'blur' }],
        investorId: [{ required: true, message: '请选择投资人', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: this.validatePhone, trigger: 'blur'}],
        barCounterShopId: [{ required: true, message: '请选择投放区域', trigger: 'blur' }],
        allocationRatio: [{ required: true, message: '请输入分账比例', trigger: 'blur' }, { validator: this.validateNumber, trigger: 'blur'}]
      },
      address: "",
      tagIndex: 0,
      inputValue: "",
      containerList: [],
      barSpuList: [],
      dataForm: {
        barSkuDTOList: [{}]
      },
      dataFormShop: {},
      shopListdata: [],
      investorList: [],
      barCounterShopList: [],
      skuList: [],
      nowDate: moment(new Date()).format('yyyy-MM-DD HH:mm:ss'),
      barCounterId: '',
    };
  },
  mounted() {
    this.barCounterId = this.$route.query.barCounterId || ''
    if (this.barCounterId) {
      api.getById({barCounterId: this.barCounterId}).then((res) => {
        this.pageQuery = res
      });
    }
    this.getPage()
    this.getShopList();
    this.getInvestorList()
    this.getBarCounterShopList()
  },
  methods: {
    getPage() {
      api.barCounterContainer().then((result) => {
        this.containerList = result.data
      });
    },
    getShopList() {
      api.barSpu(this.pageQuerys).then((pageVO) => {
        this.pageVO = pageVO
        this.pageVO.list.forEach(item => {
          item.exhibitionProdName = item.name
          item.exhibitionSeq = item.seq
          item.priceFee = item.priceFee / 100
          item.marketPriceFee = item.marketPriceFee / 100
        })
      });
    },
    copyClose() {
      this.$router.push("/barcounter/selfoperated");
    },
    getInvestorList() {
      api.investorList().then(result => {
        this.investorList = result
      })
    },
    getBarCounterShopList() {
      api.barCounterShopList().then(result=> {
        this.barCounterShopList = result
      })
    },
    barCounterChange(e) {
      const obj = this.barCounterShopList.find(item => item.barCounterShopId == e)
    },
    onFocus(record) {
      api.barSpu({spuId: record.spuId, pageNum: 1, pageSize: 10}).then(result=> {
        this.skuList = result.list[0].skus
      })
    },
    skuChange(e, row) {
      let barSkuDTOList = this.skuList.filter(item => item.skuId == e)
      row.barSkuDTOList = barSkuDTOList
    },
    // 单选
    getSelectBrandRow(row) {
      this.brandListSelections = row
    },
    shopSubmit() {
      if(JSON.stringify(this.brandListSelections) === '{}') {
        this.$message({
          message: '请选择商品',
          type: 'error',
          duration: 1500,
        })
        return
      }
      if(this.brandListSelections.barSkuDTOList && this.brandListSelections.barSkuDTOList.length > 0 && this.brandListSelections.alermLine > 0) {
        this.$refs['dataFormShop'].validate((valid) => {
          console.log(valid)
          if(valid) {
            this.brandListSelections.barSkuDTOList[0].alermLine = this.brandListSelections.alermLine
            this.pageQuery.barCounterContainerDTOList.forEach(item => {
              if (this.dataFormShop.region.indexOf(item.region) !== -1) {
                item.barSpuDTOList.push(JSON.parse(JSON.stringify(this.brandListSelections)))
              }
            })
            this.visibleShop = false;
          }
        })
      } else {
        this.$message({
          message: '请选择规格和预警线',
          type: 'error',
          duration: 1500,
        })
        return
      }
    },
    changeMap(e, cb) {
      // 输入框内容变化时的处理逻辑
      this.map = [];
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        if (e) {
          this.searchMap(e);
        }
      }, 1000);
    },
    handleAddShop() {
      this.visibleShop = true;
      this.dataFormShop = {};
      this.singleSelectBrandId = null;
      this.brandListSelections = {}
      this.pageVO.list.forEach((item, index) => {
        delete item.barSkuDTOList
        delete item.skus
        delete item.alermLine
        delete item.guige
      })
      console.log(this.pageVO)
    },
    handleEdit(record) {
      api.barSpu({spuId: record.spuId, pageNum: 1, pageSize: 10}).then(result=> {
        this.skuList = result.list[0].skus
      })
      this.visible = true;
      this.dataForm = record;
      this.dataForm.alermLine = record.barSkuDTOList[0].alermLine
      this.dataForm.guige = record.barSkuDTOList[0].barSpuId
      this.dataForm.skuName = record.barSkuDTOList[0].skuName
    },
    handleDel(index) {
      this.pageQuery.barCounterContainerDTOList[this.tagIndex].barSpuDTOList.splice(index, 1)
    },
    handleClose(tag) {
      this.pageQuery.barCounterContainerDTOList.splice(this.pageQuery.barCounterContainerDTOList[tag], 1)
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    status(index) {
      this.tagIndex = index;
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      let flag = this.pageQuery.barCounterContainerDTOList.some((item) => item.region == inputValue);
      if (this.pageQuery.barCounterContainerDTOList.length > 0 && flag) {
        this.$message.warning("货柜不能重复");
        return;
      }
      if (this.pageQuery.barCounterContainerDTOList.length > 0) {
        if (inputValue && !flag) {
          this.pageQuery.barCounterContainerDTOList.push({region: inputValue, barSpuDTOList: []});
        }
      } else {
        if (inputValue) {
          this.pageQuery.barCounterContainerDTOList.push({region: inputValue, barSpuDTOList: []});
        }
      }
      this.inputValue = "";
      this.inputVisible = false;
    },
    dataFormSubmit() {
      console.log(this.dataForm, '==============>this.dataForm')
      console.log(this.skuList, '==============>this.skuList')
      let barSkuDTOList = this.skuList.filter(item => item.spuId == this.dataForm.spuId)
      console.log(barSkuDTOList, '==============>barSkuDTOList')
      if(barSkuDTOList.length > 0) {
        let data = JSON.parse(JSON.stringify(barSkuDTOList))
        data[0].alermLine = this.dataForm.alermLine
        data[0].stock = 0
        this.$set(this.dataForm, 'barSkuDTOList', data)
        this.$forceUpdate()
      } else {
        this.dataForm.alermLine = null
        this.$set(this.dataForm, 'barSkuDTOList', [])
      }
      this.visible = false
    },    
    clearSearchInfo() {
      this.pageQuery.title = null;
      this.pageQuery.content = null;
      this.pageQuery.status = null;
      this.pageQuery.shopId = null;
      this.getPage();
    },
    validatePhone(rule, value, callback) {
      let reg = /^1[3456789]\d{9}$/
      if (!value) {
        return callback(new Error('请输入手机号'));
      }
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确手机号'));
      }
    },
    validateNumber(rule, value, callback) {
      let reg = /^\d+$/
      if (!value) {
        return callback(new Error('请输入分账比例'));
      }
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入数字'));
      }
    },
    onsave() {
      this.$refs['pageQuery'].validate((valid) => {
        console.log(valid)
        if(valid) {
          if (this.pageQuery.barCounterContainerDTOList.length > 0) {
            this.pageQuery.barCounterContainerDTOList.forEach(item => {
              if (item.barSpuDTOList && item.barSpuDTOList.length > 0) {
                const every = item.barSpuDTOList && item.barSpuDTOList.length > 0 && item.barSpuDTOList.every(element => element.barSkuDTOList && element.barSkuDTOList.length > 0)
                if (every) {
                  api.edit(this.pageQuery).then(res => {
                    this.$message({
                      message: this.$t('table.actionSuccess'),
                      type: 'success',
                      duration: 1500,
                      onClose: () => {
                        this.visible = false
                        this.pageQuery = {
                          type: null,
                          number: null,
                          investorId: null,
                          phone: null,
                          allocationRatio: null,
                          barCounterContainerDTOList: []
                        }
                        this.$router.push("/barcounter/selfoperated")
                      }
                    })
                  })
                } else {
                  this.$message.error(`请点击编辑选择商品规格`)
                }
              } else {
                this.$message.error(`柜台${item.region}请录入商品`)
                return;
              }
            })
          } else {
            this.$message.error('请添加货柜')
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    }
  },
};
</script>
    
<style lang="scss" scoped>
::v-deep.mod-hot-search {
  .el-form--inline {
    .el-form-item {
      margin-right: 20px;
    }
  }
  .container {
    width: 100%;
    height: 36px;
    display: flex;
    text-align: center;
    margin-bottom: 10px;
    overflow-x: auto;
    -webkit-scrollbar-width: none;
    -ms-overflow-style: none;
    scrollbar-width: none;
    .item {
      flex-shrink: 0;
      width: 10%;
      height: 100%;
      border-left: 1px solid #1684fc;
      border-right: 1px solid #1684fc;
      color: #1684fc;
      .el-input__inner {
        height: 34px !important;
        border-radius: 0px !important;
        border: none !important;
      }
    }
  }
  .container::-webkit-scrollbar {
    display: none; /* 隐藏Webkit内核浏览器的滚动条 */
  }
}
</style>
    